<template>
  <div class="box" ref="content_ref" tabindex="-1">
    <slot></slot>
    <Teleport to="body">
      <div
        class="tab"
        v-if="is_show"
        v-resize="menu_resize"
        :style="{ top: pos.pos_y + 'px', left: pos.pos_x+ 'px' }"
      >
        <slot name="content"></slot>
      </div>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";

const content_ref = ref(null);
const x = ref(0);
const y = ref(0);
const vw = ref(0);
const vh = ref(0);
const menu_width = ref(0);
const menu_height = ref(0);
const is_show = ref(false);

onMounted(() => {
  content_ref.value.addEventListener("contextmenu", contextmenu_handle);
  window.addEventListener("click", colse_handle,true)
  window.addEventListener("contextmenu", colse_handle,true)
  window.addEventListener("resize", resize);
  resize();
});

// onUnmounted(() => {
//   content_ref.value.removeEventListener("contextmenu", contextmenu_handle);
//   window.removeEventListener("click", colse_handle)
//   window.removeEventListener("contextmenu", colse_handle)
//   window.removeEventListener("resize", resize);
// });

const pos = computed(()=>{
  let pos_x = x.value
  let pos_y = y.value
  if(x.value > vw.value - menu_width.value){
    pos_x = x.value - menu_width.value
  }
  if(y.value > vh.value - menu_height.value){
    pos_y = vh.value - menu_height.value
  }
  return{
    pos_x,
    pos_y
  }
})

const contextmenu_handle = (e) => {
  e.preventDefault();
  x.value = e.clientX;
  y.value = e.clientY;
  is_show.value = true;
};

const colse_handle = () => {
    is_show.value = false;
};

const resize = () => {
    vw.value = document.documentElement.clientWidth;
    vh.value = document.documentElement.clientHeight;
}

const menu_resize=({ width, height })=>{
    menu_height.value = height;
    menu_width.value = width;
    console.log(width, height)
}
</script>

<style lang="less" scoped>
.box {
}
</style>
